package com.example.wuqiu.module.sys.controller;

import com.example.wuqiu.utils.ToolUtil;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
public class SysToolController {
    /**
     * pdf转word
     * */
    @PostMapping("/pdfToDoc")
    public void pdfToDoc(MultipartFile file, HttpServletResponse response) throws Exception {

        // 将MultiparFile转为File
        File pdfFile = ToolUtil.multipartToFile(file);

        // 创建Pdf工具类对象
        PdfDocument pdf = new PdfDocument();

        // 拼接Word文件名
        String projectPath = System.getProperty("user.dir");
        String name = pdfFile.getName();
        pdf.loadFromFile(projectPath + "/" + name);

        //保存为Word格式
        String fileName = pdfFile.getName().substring(0, pdfFile.getName().lastIndexOf(".")) + ".docx";
        pdf.saveToFile(fileName, FileFormat.DOCX);

        // 将问文件转为字节流返回供前端下载
        File wordFile = new File(fileName);
        response.setHeader("content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(wordFile);

            XWPFDocument document = new XWPFDocument(fis);
            // 替换Doc警告为空,
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            HashMap<String, String> map = new HashMap<>(16);
            map.put("Evaluation Warning : The document was created with Spire.PDF for java."," ");
            while (itPara.hasNext()) {
                XWPFParagraph paragraph = itPara.next();

                Set<String> set = map.keySet();
                /*
                 * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                 * 就可以把原来的文字全部替换掉了
                 */
                for (String key : set) {
                    List<XWPFRun> run = paragraph.getRuns();
                    /*
                     * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                     * 就可以把原来的文字全部替换掉了
                     */
                    for (XWPFRun xwpfRun : run) {
                        if (xwpfRun.getText(xwpfRun.getTextPosition()) != null &&
                                xwpfRun.getText(xwpfRun.getTextPosition()).equals(key)) {
                            /*
                             * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                             * 就可以把原来的文字全部替换掉了
                             */
                            xwpfRun.setText(map.get(key), 0);
                        }
                    }
                }
            }
            // 将 XWPFDocument 对象转换为 FileInputStream 或 ByteArrayInputStream 流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.write(baos);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            // 使用 BufferedInputStream 读取数据流
            bis = new BufferedInputStream(inputStream);

            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("word文件成功下载");

        } catch (Exception e) {
            log.info("word文件下载失败");
        } finally {
            if (bis != null) {
                try {
                    // 结束后关闭文件流
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    // 结束后关闭文件流
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 最后删除转换过程中生成的文件
            wordFile.delete();
            pdfFile.delete();
        }
    }
}
